package cn.iocoder.yudao.module.system.util.gugu;

import cn.iocoder.yudao.framework.common.util.http.HttpUtils;
import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
import cn.iocoder.yudao.module.system.controller.admin.gugu.gugu.CeeMajorInfo;
import cn.iocoder.yudao.module.system.controller.admin.gugu.gugu.CeeMajorQueryReqVO;
import cn.iocoder.yudao.module.system.controller.admin.gugu.gugu.CollegeEnrollmentPlanInfo;
import cn.iocoder.yudao.module.system.controller.admin.gugu.gugu.CollegeEnrollmentPlanQueryReqVO;
import cn.iocoder.yudao.module.system.controller.admin.gugu.gugu.CollegeApiResponse;
import cn.iocoder.yudao.module.system.controller.admin.gugu.gugu.CollegeInfo;
import cn.iocoder.yudao.module.system.controller.admin.gugu.gugu.CollegeQueryReqVO;
import cn.iocoder.yudao.module.system.controller.admin.gugu.gugu.CollegeScoreInfo;
import cn.iocoder.yudao.module.system.controller.admin.gugu.gugu.CollegeScoreQueryReqVO;
import cn.iocoder.yudao.module.system.controller.admin.gugu.gugu.ExaminationResult;
import cn.iocoder.yudao.module.system.controller.admin.gugu.gugu.MajorAdmissionInfo;
import cn.iocoder.yudao.module.system.controller.admin.gugu.gugu.MajorAdmissionQueryReqVO;
import cn.iocoder.yudao.module.system.controller.admin.gugu.gugu.ProvinceScoreInfo;
import cn.iocoder.yudao.module.system.controller.admin.gugu.gugu.ProvinceScoreQueryReqVO;
import cn.iocoder.yudao.module.system.controller.admin.gugu.gugu.QsRankingInfo;
import cn.iocoder.yudao.module.system.controller.admin.gugu.gugu.QsRankingQueryReqVO;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GuGuDataUtils {
    private static final String apibase = "https://api.gugudata.com";

    //高校基础信息apikey
    private static final String apiKey_school = "257KUWTX6ZUES8994QLLN5Z5PPLDTHV5";

    //一分一段apikey
    private static final String apiKey_score = "VB8WXGDWJ47VAGW54MAVGYMGTBYZNJJ3";

    //历年高考专业录取数据apikey
    private static final String apiKey_major = "JWZQJAFNR5LB7HP89R3R9CTUSX3PECKF";

    //大学高校专业数据apikey
    public static final String apiKey_major_detail = "F2G9U9BBNY3YNWSWC2CEXXBK62QJ6VC3";

    //历年高校招生计划
    private static final String apiKey_ceeline = "8N9BFH4DPAXWL4JJB5WAJYBJ3QCL77FM";

    //历年高考省录取分数线
    private static final String apiKey_province = "GLGDHX8N6N29U7L75M6FBC4LPVQYM398";

    //历年高考高校录取分数线
    private static final String apiKey_school_score = "E6X2G4QC2VC2LA3WN3K46KLCVAZKEXLM";

    //全球QS世界大学排名
    private static final String apiKey_qs_ranking = "3KPPMJEQK3EHL6PZDPXTGDEPMKQPZP4U";

    /**
     * 验证大学高校专业数据API Key是否有效
     * @param appkey 待验证的API Key
     * @return 是否有效
     */
    public static boolean validateCeeMajorApiKey(String appkey) {
        return apiKey_major_detail.equals(appkey);
    }

    /**
     * 验证历年高考专业录取数据API Key是否有效
     * @param appkey 待验证的API Key
     * @return 是否有效
     */
    public static boolean validateMajorAdmissionApiKey(String appkey) {
        return apiKey_major.equals(appkey);
    }

    /**
     * 验证一分一段数据API Key是否有效
     * @param appkey 待验证的API Key
     * @return 是否有效
     */
    public static boolean validateScoreApiKey(String appkey) {
        return apiKey_score.equals(appkey);
    }

    /**
     * 验证历年高考省录取分数线API Key是否有效
     * @param appkey 待验证的API Key
     * @return 是否有效
     */
    public static boolean validateProvinceScoreApiKey(String appkey) {
        return apiKey_province.equals(appkey);
    }

    /**
     * 验证历年高考高校录取分数线API Key是否有效
     * @param appkey 待验证的API Key
     * @return 是否有效
     */
    public static boolean validateCollegeScoreApiKey(String appkey) {
        return apiKey_school_score.equals(appkey);
    }

    /**
     * 验证全球QS世界大学排名API Key是否有效
     * @param appkey 待验证的API Key
     * @return 是否有效
     */
    public static boolean validateQsRankingApiKey(String appkey) {
        return apiKey_qs_ranking.equals(appkey);
    }


    // 添加请求频率控制
    private static final long MIN_REQUEST_INTERVAL = 1000; // 最小请求间隔（毫秒）
    private static long lastRequestTime = 0; // 上次请求时间

    /**
     * 一分一段数据查询
     * @param subjectSelection 科目选择
     * @param year 年份
     * @param provinceName 省份名称
     * @param pageIndex 页码
     * @param pageSize 每页大小
     * @return 查询结果JSON字符串
     */
    public static String getScoreSegmentJson(String subjectSelection, String year, String provinceName, Integer pageIndex, Integer pageSize) {
        try {
            // 请求频率控制
            long currentTime = System.currentTimeMillis();
            long elapsedTime = currentTime - lastRequestTime;
            if (lastRequestTime > 0 && elapsedTime < MIN_REQUEST_INTERVAL) {
                // 如果距离上次请求的时间小于最小间隔，则等待
                long sleepTime = MIN_REQUEST_INTERVAL - elapsedTime;
                Thread.sleep(sleepTime);
            }

            Map<String, String> header = new HashMap<>();
            // 添加请求头信息
            header.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
            header.put("Accept", "application/json");

            // 对参数进行 URL 编码
            String encodedProvinceName = java.net.URLEncoder.encode(provinceName, "UTF-8");
            String encodedSubjectSelection = java.net.URLEncoder.encode(subjectSelection, "UTF-8");

            String url = apibase + "/metadata/ceeline/one-score-one-section?appkey=" + apiKey_score +
                    "&year=" + year +
                    "&provinceName=" + encodedProvinceName +
                    "&subjectSelection=" + encodedSubjectSelection +
                    "&pageIndex=" + pageIndex +
                    "&pageSize=" + pageSize;

            // 发送请求并记录时间
            lastRequestTime = System.currentTimeMillis();
            String response = HttpUtils.get(url, header);

            // 检查响应是否是JSON格式
            if (response != null && (response.startsWith("{") || response.startsWith("["))) {
                return response;
            } else {
                throw new RuntimeException("服务器返回了非JSON格式的响应");
            }
        } catch (Exception e) {
            throw new RuntimeException("请求数据失败: " + e.getMessage(), e);
        }
    }

    /**
     * 从JSON响应中提取Data字段并转换为ExaminationResult列表
     * @param json JSON响应字符串
     * @return ExaminationResult列表
     */
    public static List<ExaminationResult> extractExaminationResult(String json) {
        try {
            // 检查JSON是否有效
            if (json == null || json.isEmpty() || !json.contains("Data")) {
                throw new RuntimeException("无效的JSON响应或缺少Data字段");
            }

            // 使用Jackson的ObjectMapper直接解析JSON
            com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
            com.fasterxml.jackson.databind.JsonNode rootNode = objectMapper.readTree(json);
            com.fasterxml.jackson.databind.JsonNode dataNode = rootNode.get("Data");

            if (dataNode == null || !dataNode.isArray()) {
                return new ArrayList<>();
            }

            // 使用TypeReference指定返回类型
            return objectMapper.readValue(
                    dataNode.toString(),
                    objectMapper.getTypeFactory().constructCollectionType(List.class, ExaminationResult.class)
            );
        } catch (Exception e) {
            throw new RuntimeException("解析响应数据失败: " + e.getMessage(), e);
        }
    }

    /**
     * 一步获取考试结果数据
     * @param subjectSelection 科目选择
     * @param year 年份
     * @param provinceName 省份名称
     * @param pageIndex 页码
     * @param pageSize 每页大小
     * @return 考试结果列表
     */
    public static List<ExaminationResult> getExaminationResults(String subjectSelection, String year, String provinceName, Integer pageIndex, Integer pageSize) {
        // 1. 获取JSON响应
        String json = getScoreSegmentJson(subjectSelection, year, provinceName, pageIndex, pageSize);
        // 2. 提取并转换数据
        return extractExaminationResult(json);
    }

    /**
     * 获取数据总数量
     * @param json API响应的JSON字符串
     * @return 数据总数量，如果无法获取则返回-1
     */
    public static int getTotalCount(String json) {
        try {
            // 使用Jackson的ObjectMapper直接解析JSON
            com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
            com.fasterxml.jackson.databind.JsonNode rootNode = objectMapper.readTree(json);
            com.fasterxml.jackson.databind.JsonNode dataStatusNode = rootNode.get("DataStatus");

            if (dataStatusNode != null && dataStatusNode.has("DataTotalCount")) {
                com.fasterxml.jackson.databind.JsonNode totalCountNode = dataStatusNode.get("DataTotalCount");
                if (totalCountNode.isNumber()) {
                    return totalCountNode.asInt();
                } else if (totalCountNode.isTextual()) {
                    return Integer.parseInt(totalCountNode.asText());
                }
            }
        } catch (Exception e) {
            // 解析异常时返回-1
            System.err.println("解析总数量失败: " + e.getMessage());
        }
        return -1;
    }

    /**
     * 示例方法：如何处理给定的JSON字符串
     * @param jsonStr JSON字符串
     * @return 考试结果列表
     */
    public static List<ExaminationResult> processJsonResponse(String jsonStr) {
        return extractExaminationResult(jsonStr);
    }

    /**
     * 查询高校基础信息
     * @param reqVO 查询参数
     * @return 高校信息JSON字符串
     */
    public static String getCollegeInfoJson(CollegeQueryReqVO reqVO) {
        try {
            // 请求频率控制
            long currentTime = System.currentTimeMillis();
            long elapsedTime = currentTime - lastRequestTime;
            if (lastRequestTime > 0 && elapsedTime < MIN_REQUEST_INTERVAL) {
                // 如果距离上次请求的时间小于最小间隔，则等待
                long sleepTime = MIN_REQUEST_INTERVAL - elapsedTime;
                Thread.sleep(sleepTime);
            }

            Map<String, String> header = new HashMap<>();
            // 添加请求头信息
            header.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
            header.put("Accept", "application/json");

            // 构建请求URL
            StringBuilder urlBuilder = new StringBuilder(apibase + "/location/college?appkey=" + apiKey_school);

            // 添加必需参数
            urlBuilder.append("&keywords=").append(java.net.URLEncoder.encode(reqVO.getKeywords(), "UTF-8"));

            // 添加可选参数
            if (reqVO.getPagesize() != null) {
                urlBuilder.append("&pagesize=").append(reqVO.getPagesize());
            }

            if (reqVO.getPageindex() != null) {
                urlBuilder.append("&pageindex=").append(reqVO.getPageindex());
            }

            if (reqVO.getKeywordstrict() != null) {
                urlBuilder.append("&keywordstrict=").append(reqVO.getKeywordstrict());
            }

            if (reqVO.getCollegecategory() != null && !reqVO.getCollegecategory().isEmpty()) {
                urlBuilder.append("&collegecategory=").append(java.net.URLEncoder.encode(reqVO.getCollegecategory(), "UTF-8"));
            }

            if (reqVO.getCollegetype() != null && !reqVO.getCollegetype().isEmpty()) {
                urlBuilder.append("&collegetype=").append(java.net.URLEncoder.encode(reqVO.getCollegetype(), "UTF-8"));
            }

            if (reqVO.getIs985() != null) {
                urlBuilder.append("&is985=").append(reqVO.getIs985());
            }

            if (reqVO.getIs211() != null) {
                urlBuilder.append("&is211=").append(reqVO.getIs211());
            }

            if (reqVO.getIsdualclass() != null) {
                urlBuilder.append("&isdualclass=").append(reqVO.getIsdualclass());
            }

            if (reqVO.getEdulevel() != null && !reqVO.getEdulevel().isEmpty()) {
                urlBuilder.append("&edulevel=").append(java.net.URLEncoder.encode(reqVO.getEdulevel(), "UTF-8"));
            }

            if (reqVO.getCollegeproperty() != null && !reqVO.getCollegeproperty().isEmpty()) {
                urlBuilder.append("&collegeproperty=").append(java.net.URLEncoder.encode(reqVO.getCollegeproperty(), "UTF-8"));
            }

            String url = urlBuilder.toString();

            // 发送请求并记录时间
            lastRequestTime = System.currentTimeMillis();
            String response = HttpUtils.get(url, header);

            // 检查响应是否是JSON格式
            if (response != null && (response.startsWith("{") || response.startsWith("["))) {
                return response;
            } else {
                throw new RuntimeException("服务器返回了非JSON格式的响应");
            }
        } catch (Exception e) {
            throw new RuntimeException("请求高校信息失败: " + e.getMessage(), e);
        }
    }

    /**
     * 从JSON响应中提取高校信息
     * @param json JSON响应字符串
     * @return 高校信息列表
     */
    public static List<CollegeInfo> extractCollegeInfo(String json) {
        try {
            // 检查JSON是否有效
            if (json == null || json.isEmpty()) {
                throw new RuntimeException("无效的JSON响应");
            }

            // 使用Jackson的ObjectMapper直接解析JSON
            com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
            // 配置ObjectMapper以处理各种特殊情况
            objectMapper.configure(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            objectMapper.configure(com.fasterxml.jackson.databind.DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
            objectMapper.configure(com.fasterxml.jackson.databind.DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);

            // 尝试解析新的API响应结构
            try {
                CollegeApiResponse apiResponse = objectMapper.readValue(json, CollegeApiResponse.class);
                if (apiResponse != null && apiResponse.getData() != null) {
                    return apiResponse.getData();
                }
            } catch (Exception e) {
                System.err.println("尝试解析新API响应结构失败，回退到旧结构: " + e.getMessage());
            }

            // 回退到旧的解析方式（兼容性处理）
            com.fasterxml.jackson.databind.JsonNode rootNode = objectMapper.readTree(json);
            com.fasterxml.jackson.databind.JsonNode dataNode = rootNode.get("Data");

            if (dataNode == null) {
                System.err.println("无法获取Data节点");
                return new ArrayList<>();
            }

            if (dataNode.isArray()) {
                try {
                    // 使用TypeReference指定返回类型
                    return objectMapper.readValue(
                            dataNode.toString(),
                            objectMapper.getTypeFactory().constructCollectionType(List.class, CollegeInfo.class)
                    );
                } catch (Exception e) {
                    System.err.println("解析Data数组失败: " + e.getMessage());

                    // 尝试逐个解析元素
                    List<CollegeInfo> result = new ArrayList<>();
                    for (int i = 0; i < dataNode.size(); i++) {
                        try {
                            com.fasterxml.jackson.databind.JsonNode collegeNode = dataNode.get(i);
                            CollegeInfo college = objectMapper.readValue(collegeNode.toString(), CollegeInfo.class);
                            result.add(college);
                        } catch (Exception ex) {
                            System.err.println("解析第" + (i + 1) + "个元素失败: " + ex.getMessage());
                        }
                    }

                    if (!result.isEmpty()) {
                        return result;
                    }
                    throw e; // 如果所有元素都解析失败，则抛出原始异常
                }
            } else {
                // 单个对象的情况
                try {
                    CollegeInfo college = objectMapper.readValue(dataNode.toString(), CollegeInfo.class);
                    List<CollegeInfo> result = new ArrayList<>();
                    result.add(college);
                    return result;
                } catch (Exception e) {
                    System.err.println("解析单个Data对象失败: " + e.getMessage());
                    throw e;
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("解析高校信息失败: " + e.getMessage(), e);
        }
    }

    /**
     * 获取高校信息总数量
     * @param json API响应的JSON字符串
     * @return 数据总数量，如果无法获取则返回-1
     */
    public static int getCollegeTotalCount(String json) {
        try {
            // 使用Jackson的ObjectMapper直接解析JSON
            com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
            objectMapper.configure(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

            // 尝试解析新的API响应结构
            try {
                CollegeApiResponse apiResponse = objectMapper.readValue(json, CollegeApiResponse.class);
                if (apiResponse != null && apiResponse.getDataStatus() != null && 
                    apiResponse.getDataStatus().getDataTotalCount() != null) {
                    return apiResponse.getDataStatus().getDataTotalCount();
                }
            } catch (Exception e) {
                System.err.println("尝试解析新API响应结构的总数失败，回退到旧结构: " + e.getMessage());
            }

            // 回退到旧的解析方式（兼容性处理）
            com.fasterxml.jackson.databind.JsonNode rootNode = objectMapper.readTree(json);
            com.fasterxml.jackson.databind.JsonNode dataStatusNode = rootNode.get("DataStatus");

            if (dataStatusNode != null && dataStatusNode.has("DataTotalCount")) {
                com.fasterxml.jackson.databind.JsonNode totalCountNode = dataStatusNode.get("DataTotalCount");
                if (totalCountNode.isNumber()) {
                    return totalCountNode.asInt();
                } else if (totalCountNode.isTextual()) {
                    return Integer.parseInt(totalCountNode.asText());
                }
            }
        } catch (Exception e) {
            // 解析异常时返回-1
            System.err.println("解析高校信息总数量失败: " + e.getMessage());
        }
        return -1;
    }

    /**
     * 查询高校信息
     * @param reqVO 查询参数
     * @return 高校信息列表和总数量
     */
    public static Map<String, Object> getCollegeInfo(CollegeQueryReqVO reqVO) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 获取JSON响应
            String json = getCollegeInfoJson(reqVO);

            // 提取高校信息
            List<CollegeInfo> collegeInfoList = extractCollegeInfo(json);

            // 获取总数量
            int totalCount = getCollegeTotalCount(json);

            // 构建返回结果
            result.put("success", true);
            result.put("collegeList", collegeInfoList);
            result.put("totalCount", totalCount);
            result.put("pageIndex", reqVO.getPageindex());
            result.put("pageSize", reqVO.getPagesize());

            // 计算总页数
            int totalPages = (int) Math.ceil((double) totalCount / reqVO.getPagesize());
            result.put("totalPages", totalPages);

            return result;
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询高校信息失败: " + e.getMessage());
            return result;
        }
    }

    /**
     * 查询历年高考专业录取数据
     * @param reqVO 查询参数
     * @return 专业录取数据JSON字符串
     */
    public static String getMajorAdmissionJson(MajorAdmissionQueryReqVO reqVO) {
        try {
            // 请求频率控制
            long currentTime = System.currentTimeMillis();
            long elapsedTime = currentTime - lastRequestTime;
            if (lastRequestTime > 0 && elapsedTime < MIN_REQUEST_INTERVAL) {
                // 如果距离上次请求的时间小于最小间隔，则等待
                long sleepTime = MIN_REQUEST_INTERVAL - elapsedTime;
                Thread.sleep(sleepTime);
            }

            Map<String, String> header = new HashMap<>();
            // 添加请求头信息
            header.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
            header.put("Accept", "application/json");

            // 构建请求URL
            StringBuilder urlBuilder = new StringBuilder(apibase + "/metadata/ceemajorline?appkey=" + apiKey_major);

            // 添加必需参数
            urlBuilder.append("&pageindex=").append(reqVO.getPageindex());
            urlBuilder.append("&pagesize=").append(reqVO.getPagesize());

            // 添加可选参数
            if (reqVO.getEnrollprovince() != null && !reqVO.getEnrollprovince().isEmpty()) {
                urlBuilder.append("&enrollprovince=").append(java.net.URLEncoder.encode(reqVO.getEnrollprovince(), "UTF-8"));
            }

            if (reqVO.getSchoolname() != null && !reqVO.getSchoolname().isEmpty()) {
                urlBuilder.append("&schoolname=").append(java.net.URLEncoder.encode(reqVO.getSchoolname(), "UTF-8"));
            }

            if (reqVO.getMajorname() != null && !reqVO.getMajorname().isEmpty()) {
                urlBuilder.append("&majorname=").append(java.net.URLEncoder.encode(reqVO.getMajorname(), "UTF-8"));
            }

            if (reqVO.getMajornamestrict() != null) {
                urlBuilder.append("&majornamestrict=").append(reqVO.getMajornamestrict());
            }

            if (reqVO.getSpecialid() != null) {
                urlBuilder.append("&specialid=").append(reqVO.getSpecialid());
            }

            if (reqVO.getYear() != null && reqVO.getYear() != 0) {
                urlBuilder.append("&year=").append(reqVO.getYear());
            }

            if (reqVO.getMin() != null && reqVO.getMin() != 0) {
                urlBuilder.append("&min=").append(reqVO.getMin());
            }

            if (reqVO.getBatchname() != null && !reqVO.getBatchname().isEmpty()) {
                urlBuilder.append("&batchname=").append(java.net.URLEncoder.encode(reqVO.getBatchname(), "UTF-8"));
            }

            if (reqVO.getTypename() != null && !reqVO.getTypename().isEmpty()) {
                urlBuilder.append("&typename=").append(java.net.URLEncoder.encode(reqVO.getTypename(), "UTF-8"));
            }

            if (reqVO.getSchooluuid() != null && !reqVO.getSchooluuid().isEmpty()) {
                urlBuilder.append("&schooluuid=").append(reqVO.getSchooluuid());
            }

            if (reqVO.getMinrange() != null && !reqVO.getMinrange().isEmpty()) {
                urlBuilder.append("&minrange=").append(reqVO.getMinrange());
            }

            if (reqVO.getSubjectselection() != null && !reqVO.getSubjectselection().isEmpty()) {
                urlBuilder.append("&subjectselection=").append(java.net.URLEncoder.encode(reqVO.getSubjectselection(), "UTF-8"));
            }

            String url = urlBuilder.toString();

            // 发送请求并记录时间
            lastRequestTime = System.currentTimeMillis();
            String response = HttpUtils.get(url, header);

            // 检查响应是否是JSON格式
            if (response != null && (response.startsWith("{") || response.startsWith("["))) {
                return response;
            } else {
                throw new RuntimeException("服务器返回了非JSON格式的响应");
            }
        } catch (Exception e) {
            throw new RuntimeException("请求历年高考专业录取数据失败: " + e.getMessage(), e);
        }
    }

    /**
     * 从JSON响应中提取历年高考专业录取数据
     * @param json JSON响应字符串
     * @return 历年高考专业录取数据列表
     */
    public static List<MajorAdmissionInfo> extractMajorAdmissionInfo(String json) {
        try {
            // 检查JSON是否有效
            if (json == null || json.isEmpty() || !json.contains("Data")) {
                throw new RuntimeException("无效的JSON响应或缺少Data字段");
            }

            // 使用Jackson的ObjectMapper直接解析JSON
            com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
            // 配置ObjectMapper以处理各种特殊情况
            objectMapper.configure(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            objectMapper.configure(com.fasterxml.jackson.databind.DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
            objectMapper.configure(com.fasterxml.jackson.databind.DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);

            com.fasterxml.jackson.databind.JsonNode rootNode = objectMapper.readTree(json);
            com.fasterxml.jackson.databind.JsonNode dataNode = rootNode.get("Data");

            if (dataNode == null || !dataNode.isArray()) {
                System.err.println("无法获取Data数组节点");
                return new ArrayList<>();
            }

            try {
                // 使用TypeReference指定返回类型
                return objectMapper.readValue(
                        dataNode.toString(),
                        objectMapper.getTypeFactory().constructCollectionType(List.class, MajorAdmissionInfo.class)
                );
            } catch (Exception e) {
                System.err.println("解析Data数组失败: " + e.getMessage());

                // 尝试逐个解析元素
                List<MajorAdmissionInfo> result = new ArrayList<>();
                for (int i = 0; i < dataNode.size(); i++) {
                    try {
                        com.fasterxml.jackson.databind.JsonNode itemNode = dataNode.get(i);
                        MajorAdmissionInfo item = objectMapper.readValue(itemNode.toString(), MajorAdmissionInfo.class);
                        result.add(item);
                    } catch (Exception ex) {
                        System.err.println("解析第" + (i + 1) + "个元素失败: " + ex.getMessage());
                    }
                }

                if (!result.isEmpty()) {
                    return result;
                }
                throw e; // 如果所有元素都解析失败，则抛出原始异常
            }
        } catch (Exception e) {
            throw new RuntimeException("解析历年高考专业录取数据失败: " + e.getMessage(), e);
        }
    }

    /**
     * 获取历年高考专业录取数据总数量和高校数量
     * @param json API响应的JSON字符串
     * @return 包含总数量和高校数量的Map
     */
    public static Map<String, Integer> getMajorAdmissionCounts(String json) {
        Map<String, Integer> result = new HashMap<>();
        result.put("totalCount", -1);
        result.put("distinctSchoolCount", -1);

        try {
            // 使用Jackson的ObjectMapper直接解析JSON
            com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
            com.fasterxml.jackson.databind.JsonNode rootNode = objectMapper.readTree(json);
            com.fasterxml.jackson.databind.JsonNode dataStatusNode = rootNode.get("DataStatus");

            if (dataStatusNode != null) {
                // 获取总数据量
                if (dataStatusNode.has("DataTotalCount")) {
                    com.fasterxml.jackson.databind.JsonNode totalCountNode = dataStatusNode.get("DataTotalCount");
                    if (totalCountNode.isNumber()) {
                        result.put("totalCount", totalCountNode.asInt());
                    } else if (totalCountNode.isTextual()) {
                        result.put("totalCount", Integer.parseInt(totalCountNode.asText()));
                    }
                }

                // 获取高校数量
                if (dataStatusNode.has("DistinctSchoolCount")) {
                    com.fasterxml.jackson.databind.JsonNode schoolCountNode = dataStatusNode.get("DistinctSchoolCount");
                    if (schoolCountNode.isNumber()) {
                        result.put("distinctSchoolCount", schoolCountNode.asInt());
                    } else if (schoolCountNode.isTextual()) {
                        result.put("distinctSchoolCount", Integer.parseInt(schoolCountNode.asText()));
                    }
                }
            }
        } catch (Exception e) {
            // 解析异常时返回默认值
            System.err.println("解析历年高考专业录取数据总数量失败: " + e.getMessage());
        }

        return result;
    }

    /**
     * 查询历年高考专业录取数据
     * @param reqVO 查询参数
     * @return 历年高考专业录取数据和总数量
     */
    public static Map<String, Object> getMajorAdmissionInfo(MajorAdmissionQueryReqVO reqVO) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 检查必需参数
            if ((reqVO.getEnrollprovince() == null || reqVO.getEnrollprovince().isEmpty()) &&
                (reqVO.getSchoolname() == null || reqVO.getSchoolname().isEmpty()) &&
                (reqVO.getMajorname() == null || reqVO.getMajorname().isEmpty()) &&
                reqVO.getSpecialid() == null) {
                result.put("success", false);
                result.put("message", "enrollprovince、schoolname、majorname、specialId 四个参数都不是必选参数，但不可同时为空");
                return result;
            }

            // 获取JSON响应
            String json = getMajorAdmissionJson(reqVO);

            // 提取历年高考专业录取数据
            List<MajorAdmissionInfo> admissionList = extractMajorAdmissionInfo(json);

            // 获取总数量和高校数量
            Map<String, Integer> counts = getMajorAdmissionCounts(json);
            int totalCount = counts.get("totalCount");
            int distinctSchoolCount = counts.get("distinctSchoolCount");

            // 构建返回结果
            result.put("success", true);
            result.put("admissionList", admissionList);
            result.put("totalCount", totalCount);
            result.put("distinctSchoolCount", distinctSchoolCount);
            result.put("pageIndex", reqVO.getPageindex());
            result.put("pageSize", reqVO.getPagesize());

            // 计算总页数
            int totalPages = (int) Math.ceil((double) totalCount / reqVO.getPagesize());
            result.put("totalPages", totalPages);

            return result;
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询历年高考专业录取数据失败: " + e.getMessage());
            return result;
        }
    }

    /**
     * 根据用户分数查询排名信息
     * @param year 年份
     * @param provinceName 省份名称
     * @param subjectSelection 选科类型
     * @param score 用户分数
     * @return 排名信息
     */
    public static Map<String, Object> getUserRankingInfo(String year, String provinceName, String subjectSelection, Integer score) {
        Map<String, Object> result = new HashMap<>();

        try {
            // API最大允许的pageSize是20
            final int pageSize = 20;
            int currentPage = 1;
            ExaminationResult userRanking = null;
            int totalCount = -1;

            // 先获取第一页数据，同时获取总数据量
            String firstPageJson = getScoreSegmentJson(subjectSelection, year, provinceName, currentPage, pageSize);
            List<ExaminationResult> firstPageResults = extractExaminationResult(firstPageJson);
            totalCount = getTotalCount(firstPageJson);

            // 如果没有数据，直接返回
            if (firstPageResults == null || firstPageResults.isEmpty()) {
                result.put("success", false);
                result.put("message", "未找到相关数据");
                return result;
            }

            // 在第一页中查找匹配的分数区间
            for (ExaminationResult examResult : firstPageResults) {
                if (isScoreInRange(examResult.getExaminationScore(), score)) {
                    userRanking = examResult;
                    break;
                }
            }

            // 如果第一页没有找到，并且有更多页数据，继续查询
            if (userRanking == null && totalCount > pageSize) {
                // 计算需要查询的页数
                int totalPages = (int) Math.ceil((double) totalCount / pageSize);
                // 限制最大页数，防止请求过多
                totalPages = Math.min(totalPages, 1000);

                // 如果第一页有数据，分析分数分布情况，优化查询策略
                int highestScore = -1;
                int lowestScore = Integer.MAX_VALUE;

                // 分析第一页数据的分数范围
                for (ExaminationResult examResult : firstPageResults) {
                    String scoreRangeStr = examResult.getExaminationScore();
                    if (scoreRangeStr != null) {
                        if (scoreRangeStr.contains("-")) {
                            // 如果是区间，取区间的最大值和最小值
                            String[] parts = scoreRangeStr.split("-");
                            try {
                                int minScore = Integer.parseInt(parts[0]);
                                int maxScore = Integer.parseInt(parts[1]);
                                highestScore = Math.max(highestScore, maxScore);
                                lowestScore = Math.min(lowestScore, minScore);
                            } catch (NumberFormatException e) {
                                // 忽略解析错误
                            }
                        } else {
                            // 如果是单一分数
                            try {
                                int exactScore = Integer.parseInt(scoreRangeStr);
                                highestScore = Math.max(highestScore, exactScore);
                                lowestScore = Math.min(lowestScore, exactScore);
                            } catch (NumberFormatException e) {
                                // 忽略解析错误
                            }
                        }
                    }
                }

                // 根据分数大小估算可能的页码，优化查询顺序
                // 假设分数越高，排名越靠前，分数越低，排名越靠后
                int startPage = 2;
                int endPage = totalPages;

                // 根据第一页数据分析结果决定查询策略
                // 如果用户分数接近第一页的最高分，从前往后查询
                // 如果用户分数接近第一页的最低分，从后往前查询
                if (highestScore > 0 && lowestScore < Integer.MAX_VALUE) {
                    // 如果用户分数接近最高分，从前往后查询
                    if (Math.abs(score - highestScore) <= Math.abs(score - lowestScore)) {
                        for (currentPage = startPage; currentPage <= endPage && userRanking == null; currentPage++) {
                            try {
                                List<ExaminationResult> pageResults = getExaminationResults(subjectSelection, year, provinceName, currentPage, pageSize);

                                if (pageResults == null || pageResults.isEmpty()) {
                                    break;
                                }

                                // 在当前页中查找匹配的分数区间
                                for (ExaminationResult examResult : pageResults) {
                                    if (isScoreInRange(examResult.getExaminationScore(), score)) {
                                        userRanking = examResult;
                                        break;
                                    }
                                }
                            } catch (Exception e) {
                                // 单个页面查询失败不应该影响整个查询过程
                                System.err.println("查询第" + currentPage + "页失败: " + e.getMessage());
                                // 等待一下再继续，避免请求频率过高
                                try {
                                    Thread.sleep(MIN_REQUEST_INTERVAL);
                                } catch (InterruptedException ie) {
                                    Thread.currentThread().interrupt();
                                }
                            }
                        }
                    } else { // 如果用户分数接近最低分，从后往前查询
                        for (currentPage = endPage; currentPage >= startPage && userRanking == null; currentPage--) {
                            try {
                                List<ExaminationResult> pageResults = getExaminationResults(subjectSelection, year, provinceName, currentPage, pageSize);

                                if (pageResults == null || pageResults.isEmpty()) {
                                    continue;
                                }

                                // 在当前页中查找匹配的分数区间
                                for (ExaminationResult examResult : pageResults) {
                                    if (isScoreInRange(examResult.getExaminationScore(), score)) {
                                        userRanking = examResult;
                                        break;
                                    }
                                }
                            } catch (Exception e) {
                                // 单个页面查询失败不应该影响整个查询过程
                                System.err.println("查询第" + currentPage + "页失败: " + e.getMessage());
                                // 等待一下再继续，避免请求频率过高
                                try {
                                    Thread.sleep(MIN_REQUEST_INTERVAL);
                                } catch (InterruptedException ie) {
                                    Thread.currentThread().interrupt();
                                }
                            }
                        }
                    }
                } else { // 如果无法分析分数分布，使用默认策略
                    // 如果分数较高，从前往后查询
                    if (score >= 600) { // 假设600分是高分界限，可以根据实际情况调整
                        for (currentPage = startPage; currentPage <= endPage && userRanking == null; currentPage++) {
                            try {
                                List<ExaminationResult> pageResults = getExaminationResults(subjectSelection, year, provinceName, currentPage, pageSize);

                                if (pageResults == null || pageResults.isEmpty()) {
                                    break;
                                }

                                // 在当前页中查找匹配的分数区间
                                for (ExaminationResult examResult : pageResults) {
                                    if (isScoreInRange(examResult.getExaminationScore(), score)) {
                                        userRanking = examResult;
                                        break;
                                    }
                                }
                            } catch (Exception e) {
                                // 单个页面查询失败不应该影响整个查询过程
                                System.err.println("查询第" + currentPage + "页失败: " + e.getMessage());
                                // 等待一下再继续，避免请求频率过高
                                try {
                                    Thread.sleep(MIN_REQUEST_INTERVAL);
                                } catch (InterruptedException ie) {
                                    Thread.currentThread().interrupt();
                                }
                            }
                        }
                    } else { // 如果分数较低，从后往前查询
                        for (currentPage = endPage; currentPage >= startPage && userRanking == null; currentPage--) {
                            try {
                                List<ExaminationResult> pageResults = getExaminationResults(subjectSelection, year, provinceName, currentPage, pageSize);

                                if (pageResults == null || pageResults.isEmpty()) {
                                    continue;
                                }

                                // 在当前页中查找匹配的分数区间
                                for (ExaminationResult examResult : pageResults) {
                                    if (isScoreInRange(examResult.getExaminationScore(), score)) {
                                        userRanking = examResult;
                                        break;
                                    }
                                }
                            } catch (Exception e) {
                                // 单个页面查询失败不应该影响整个查询过程
                                System.err.println("查询第" + currentPage + "页失败: " + e.getMessage());
                                // 等待一下再继续，避免请求频率过高
                                try {
                                    Thread.sleep(MIN_REQUEST_INTERVAL);
                                } catch (InterruptedException ie) {
                                    Thread.currentThread().interrupt();
                                }
                            }
                        }
                    }
                }
            }

            if (userRanking == null) {
                result.put("success", false);
                result.put("message", "未找到对应分数的排名信息");
                return result;
            }

            // 构建返回结果
            result.put("success", true);
            result.put("ranking", userRanking.getRanking());
            result.put("rankingRange", userRanking.getRankingRange());
            result.put("totalCandidates", userRanking.getTotalCandidates());
            result.put("admissionBatchName", userRanking.getAdmissionBatchName());
            result.put("minimumAdmissionScore", userRanking.getMinimumAdmissionScore());
            result.put("historicalScores", userRanking.getHistoricalScores());
            result.put("totalCount", totalCount); // 添加总数据量信息

            return result;
        } catch (Exception e) {
            result.put("success", false);
            // 提取更有用的错误信息
            String errorMsg = e.getMessage();
            if (e.getCause() != null && e.getCause().getMessage() != null) {
                errorMsg = e.getCause().getMessage();
            }

            // 如果错误信息包含 HTML 标签，可能是服务器返回了错误页面
            if (errorMsg.contains("<html") || errorMsg.contains("<!doctype")) {
                errorMsg = "服务器返回了错误页面，请检查参数是否正确";
            }

            result.put("message", "查询失败: " + errorMsg);
            return result;
        }
    }

    /**
     * 查询大学高校专业数据
     * @param reqVO 查询参数
     * @return 专业数据JSON字符串
     */
    public static String getCeeMajorJson(CeeMajorQueryReqVO reqVO) {
        try {
            // 请求频率控制
            long currentTime = System.currentTimeMillis();
            long elapsedTime = currentTime - lastRequestTime;
            if (lastRequestTime > 0 && elapsedTime < MIN_REQUEST_INTERVAL) {
                // 如果距离上次请求的时间小于最小间隔，则等待
                long sleepTime = MIN_REQUEST_INTERVAL - elapsedTime;
                Thread.sleep(sleepTime);
            }

            Map<String, String> header = new HashMap<>();
            // 添加请求头信息
            header.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
            header.put("Accept", "application/json");

            // 构建请求URL
            StringBuilder urlBuilder = new StringBuilder(apibase + "/metadata/ceemajor?appkey=" + apiKey_major_detail);

            // 添加可选参数
            if (reqVO.getKeywords() != null && !reqVO.getKeywords().isEmpty()) {
                urlBuilder.append("&keywords=").append(java.net.URLEncoder.encode(reqVO.getKeywords(), "UTF-8"));
            }

            if (reqVO.getPageSize() != null) {
                urlBuilder.append("&pagesize=").append(reqVO.getPageSize());
            }

            if (reqVO.getPageIndex() != null) {
                urlBuilder.append("&pageindex=").append(reqVO.getPageIndex());
            }

            String url = urlBuilder.toString();

            // 发送请求并记录时间
            lastRequestTime = System.currentTimeMillis();
            String response = HttpUtils.get(url, header);

            // 检查响应是否是JSON格式
            if (response != null && (response.startsWith("{") || response.startsWith("["))) {
                return response;
            } else {
                throw new RuntimeException("服务器返回了非JSON格式的响应");
            }
        } catch (Exception e) {
            throw new RuntimeException("请求大学高校专业数据失败: " + e.getMessage(), e);
        }
    }

    /**
     * 从JSON响应中提取大学高校专业数据
     * @param json JSON响应字符串
     * @return 大学高校专业数据列表
     */
    public static List<CeeMajorInfo> extractCeeMajorInfo(String json) {
        try {
            // 检查JSON是否有效
            if (json == null || json.isEmpty() || !json.contains("Data")) {
                throw new RuntimeException("无效的JSON响应或缺少Data字段");
            }

            // 使用Jackson的ObjectMapper直接解析JSON
            com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
            // 配置ObjectMapper以处理各种特殊情况
            objectMapper.configure(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            objectMapper.configure(com.fasterxml.jackson.databind.DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
            objectMapper.configure(com.fasterxml.jackson.databind.DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);

            com.fasterxml.jackson.databind.JsonNode rootNode = objectMapper.readTree(json);
            com.fasterxml.jackson.databind.JsonNode dataNode = rootNode.get("Data");

            if (dataNode == null || !dataNode.isArray()) {
                System.err.println("无法获取Data数组节点");
                return new ArrayList<>();
            }

            try {
                // 使用TypeReference指定返回类型
                return objectMapper.readValue(
                        dataNode.toString(),
                        objectMapper.getTypeFactory().constructCollectionType(List.class, CeeMajorInfo.class)
                );
            } catch (Exception e) {
                System.err.println("解析Data数组失败: " + e.getMessage());

                // 尝试逐个解析元素
                List<CeeMajorInfo> result = new ArrayList<>();
                for (int i = 0; i < dataNode.size(); i++) {
                    try {
                        com.fasterxml.jackson.databind.JsonNode itemNode = dataNode.get(i);
                        CeeMajorInfo item = objectMapper.readValue(itemNode.toString(), CeeMajorInfo.class);
                        result.add(item);
                    } catch (Exception ex) {
                        System.err.println("解析第" + (i + 1) + "个元素失败: " + ex.getMessage());
                    }
                }

                if (!result.isEmpty()) {
                    return result;
                }
                throw e; // 如果所有元素都解析失败，则抛出原始异常
            }
        } catch (Exception e) {
            throw new RuntimeException("解析大学高校专业数据失败: " + e.getMessage(), e);
        }
    }

    /**
     * 获取大学高校专业数据总数量
     * @param json API响应的JSON字符串
     * @return 数据总数量，如果无法获取则返回-1
     */
    public static int getCeeMajorTotalCount(String json) {
        try {
            // 使用Jackson的ObjectMapper直接解析JSON
            com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
            com.fasterxml.jackson.databind.JsonNode rootNode = objectMapper.readTree(json);
            com.fasterxml.jackson.databind.JsonNode dataStatusNode = rootNode.get("DataStatus");

            if (dataStatusNode != null && dataStatusNode.has("DataTotalCount")) {
                com.fasterxml.jackson.databind.JsonNode totalCountNode = dataStatusNode.get("DataTotalCount");
                if (totalCountNode.isNumber()) {
                    return totalCountNode.asInt();
                } else if (totalCountNode.isTextual()) {
                    return Integer.parseInt(totalCountNode.asText());
                }
            }
        } catch (Exception e) {
            // 解析异常时返回-1
            System.err.println("解析大学高校专业数据总数量失败: " + e.getMessage());
        }
        return -1;
    }

    /**
     * 查询大学高校专业数据
     * @param reqVO 查询参数
     * @return 大学高校专业数据和总数量
     */
    public static Map<String, Object> getCeeMajorInfo(CeeMajorQueryReqVO reqVO) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 获取JSON响应
            String json = getCeeMajorJson(reqVO);

            // 提取大学高校专业数据
            List<CeeMajorInfo> majorList = extractCeeMajorInfo(json);

            // 获取总数量
            int totalCount = getCeeMajorTotalCount(json);

            // 构建返回结果
            result.put("success", true);
            result.put("majorList", majorList);
            result.put("totalCount", totalCount);
            result.put("pageIndex", reqVO.getPageIndex());
            result.put("pageSize", reqVO.getPageSize());

            // 计算总页数
            int totalPages = (int) Math.ceil((double) totalCount / reqVO.getPageSize());
            result.put("totalPages", totalPages);

            return result;
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询大学高校专业数据失败: " + e.getMessage());
            return result;
        }
    }

    /**
     * 查询大学高校专业数据，自动获取所有页的数据
     * @param reqVO 查询参数
     * @return 大学高校专业数据和总数量
     */
    public static Map<String, Object> getCeeMajorInfoAll(CeeMajorQueryReqVO reqVO) {
        Map<String, Object> result = new HashMap<>();
        List<CeeMajorInfo> allMajorList = new ArrayList<>();

        try {
            // 获取第一页数据，用于获取总数量和总页数
            CeeMajorQueryReqVO firstPageReqVO = new CeeMajorQueryReqVO();
            firstPageReqVO.setKeywords(reqVO.getKeywords());
            firstPageReqVO.setPageSize(20); // 使用最大页面大小
            firstPageReqVO.setPageIndex(1);

            Map<String, Object> firstPageResult = getCeeMajorInfo(firstPageReqVO);

            if (!Boolean.TRUE.equals(firstPageResult.get("success"))) {
                return firstPageResult; // 如果第一页查询失败，直接返回错误
            }

            // 获取总数量和总页数
            int totalCount = (Integer) firstPageResult.get("totalCount");
            int totalPages = (Integer) firstPageResult.get("totalPages");

            // 添加第一页的数据
            allMajorList.addAll((List<CeeMajorInfo>) firstPageResult.get("majorList"));

            // 如果有多页，获取其他页的数据
            if (totalPages > 1) {
                for (int pageIndex = 2; pageIndex <= totalPages; pageIndex++) {
                    CeeMajorQueryReqVO pageReqVO = new CeeMajorQueryReqVO();
                    pageReqVO.setKeywords(reqVO.getKeywords());
                    pageReqVO.setPageSize(20); // 使用最大页面大小
                    pageReqVO.setPageIndex(pageIndex);

                    Map<String, Object> pageResult = getCeeMajorInfo(pageReqVO);

                    if (Boolean.TRUE.equals(pageResult.get("success"))) {
                        List<CeeMajorInfo> pageMajorList = (List<CeeMajorInfo>) pageResult.get("majorList");
                        if (pageMajorList != null && !pageMajorList.isEmpty()) {
                            allMajorList.addAll(pageMajorList);
                        }
                    } else {
                        // 如果单页查询失败，记录错误但不中断整个查询
                        System.err.println("查询第" + pageIndex + "页失败: " + pageResult.get("message"));
                    }
                }
            }

            // 构建返回结果
            result.put("success", true);
            result.put("majorList", allMajorList);
            result.put("totalCount", totalCount);
            result.put("pageIndex", 1); // 因为返回了所有数据，所以页码固定为1
            result.put("pageSize", allMajorList.size()); // 页面大小就是所有数据的数量
            result.put("totalPages", 1); // 因为返回了所有数据，所以总页数固定为1
            result.put("isAllData", true); // 标记这是所有数据

            return result;
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询大学高校专业数据失败: " + e.getMessage());
            return result;
        }
    }

    /**
     * 批量保存高校基础信息到数据库
     * @param collegeInfoList 高校基础信息列表
     * @return 保存成功的数量
     */
    public static int saveCollegeInfoToDatabase(List<CollegeInfo> collegeInfoList) {
        // 这个方法需要在Service层实现，这里只是提供接口
        // 实际的数据库操作应该通过Spring的Service层来完成
        throw new UnsupportedOperationException("此方法应该通过CollegeService来调用");
    }

    /**
     * 从API获取高校基础信息并保存到数据库
     * @param keywords 搜索关键字
     * @param pageIndex 页码
     * @param pageSize 每页大小
     * @return 保存结果
     */
    public static Map<String, Object> importCollegeInfoToDatabase(String keywords, Integer pageIndex, Integer pageSize) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 构建请求参数
            CollegeQueryReqVO reqVO = new CollegeQueryReqVO();
            reqVO.setKeywords(keywords != null ? keywords : "");
            reqVO.setPagesize(pageSize != null ? pageSize : 20);
            reqVO.setPageindex(pageIndex != null ? pageIndex : 1);

            // 获取高校信息
            Map<String, Object> apiResult = getCollegeInfo(reqVO);

            if (!Boolean.TRUE.equals(apiResult.get("success"))) {
                result.put("success", false);
                result.put("message", "API调用失败: " + apiResult.get("message"));
                return result;
            }

            @SuppressWarnings("unchecked")
            List<CollegeInfo> collegeList = (List<CollegeInfo>) apiResult.get("collegeList");

            if (collegeList == null || collegeList.isEmpty()) {
                result.put("success", true);
                result.put("message", "没有获取到高校数据");
                result.put("importedCount", 0);
                return result;
            }

            // 注意：实际的数据库保存操作需要通过Service层来完成
            // 这里只是返回获取到的数据，具体的保存逻辑在CollegeService中实现
            result.put("success", true);
            result.put("collegeList", collegeList);
            result.put("totalCount", apiResult.get("totalCount"));
            result.put("pageIndex", pageIndex);
            result.put("pageSize", pageSize);
            result.put("message", "成功获取 " + collegeList.size() + " 条高校数据");

        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "导入高校数据失败: " + e.getMessage());
        }

        return result;
    }

    /**
     * 判断分数是否在区间内
     * @param scoreRange 分数区间字符串，如"673-750"或"672"
     * @param score 待判断的分数
     * @return 是否在区间内
     */
    private static boolean isScoreInRange(String scoreRange, Integer score) {
        if (scoreRange == null || score == null) {
            return false;
        }

        // 如果是单一分数
        if (!scoreRange.contains("-")) {
            try {
                int exactScore = Integer.parseInt(scoreRange);
                return score == exactScore;
            } catch (NumberFormatException e) {
                return false;
            }
        }

        // 如果是分数区间
        String[] parts = scoreRange.split("-");
        if (parts.length != 2) {
            return false;
        }

        try {
            int minScore = Integer.parseInt(parts[0]);
            int maxScore = Integer.parseInt(parts[1]);
            return score >= minScore && score <= maxScore;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    /**
     * 验证历年高校招生计划API Key是否有效
     * @param appkey 待验证的API Key
     * @return 是否有效
     */
    public static boolean validateCollegeEnrollmentPlanApiKey(String appkey) {
        return apiKey_ceeline.equals(appkey);
    }

    /**
     * 查询历年高校招生计划数据
     * @param reqVO 查询参数
     * @return 招生计划数据JSON字符串
     */
    public static String getCollegeEnrollmentPlanJson(CollegeEnrollmentPlanQueryReqVO reqVO) {
        try {
            // 请求频率控制
            long currentTime = System.currentTimeMillis();
            long elapsedTime = currentTime - lastRequestTime;
            if (lastRequestTime > 0 && elapsedTime < MIN_REQUEST_INTERVAL) {
                // 如果距离上次请求的时间小于最小间隔，则等待
                long sleepTime = MIN_REQUEST_INTERVAL - elapsedTime;
                Thread.sleep(sleepTime);
            }

            Map<String, String> header = new HashMap<>();
            // 添加请求头信息
            header.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
            header.put("Accept", "application/json");

            // 构建请求URL
            StringBuilder urlBuilder = new StringBuilder(apibase + "/metadata/college-enrollment-plan?appkey=" + apiKey_ceeline);

            // 添加必需参数
            urlBuilder.append("&pageIndex=").append(reqVO.getPageIndex());
            urlBuilder.append("&pageSize=").append(reqVO.getPageSize());

            // 添加可选参数
            if (reqVO.getCollegeMajorName() != null && !reqVO.getCollegeMajorName().isEmpty()) {
                urlBuilder.append("&collegemajorname=").append(java.net.URLEncoder.encode(reqVO.getCollegeMajorName(), "UTF-8"));
            }

            if (reqVO.getYear() != null && reqVO.getYear() != 0) {
                urlBuilder.append("&year=").append(reqVO.getYear());
            }

            if (reqVO.getSchoolName() != null && !reqVO.getSchoolName().isEmpty()) {
                urlBuilder.append("&schoolname=").append(java.net.URLEncoder.encode(reqVO.getSchoolName(), "UTF-8"));
            }

            if (reqVO.getProvinceName() != null && !reqVO.getProvinceName().isEmpty()) {
                urlBuilder.append("&provincename=").append(java.net.URLEncoder.encode(reqVO.getProvinceName(), "UTF-8"));
            }

            if (reqVO.getClassOne() != null && !reqVO.getClassOne().isEmpty()) {
                urlBuilder.append("&classone=").append(java.net.URLEncoder.encode(reqVO.getClassOne(), "UTF-8"));
            }

            if (reqVO.getClassTwo() != null && !reqVO.getClassTwo().isEmpty()) {
                urlBuilder.append("&classtwo=").append(java.net.URLEncoder.encode(reqVO.getClassTwo(), "UTF-8"));
            }

            if (reqVO.getBatchName() != null && !reqVO.getBatchName().isEmpty()) {
                urlBuilder.append("&batchname=").append(java.net.URLEncoder.encode(reqVO.getBatchName(), "UTF-8"));
            }

            if (reqVO.getType() != null && !reqVO.getType().isEmpty()) {
                urlBuilder.append("&type=").append(java.net.URLEncoder.encode(reqVO.getType(), "UTF-8"));
            }

            if (reqVO.getSchoolUuid() != null && !reqVO.getSchoolUuid().isEmpty()) {
                urlBuilder.append("&schooluuid=").append(reqVO.getSchoolUuid());
            }

            String url = urlBuilder.toString();

            // 发送请求并记录时间
            lastRequestTime = System.currentTimeMillis();
            String response = HttpUtils.get(url, header);

            // 检查响应是否是JSON格式
            if (response != null && (response.startsWith("{") || response.startsWith("["))) {
                return response;
            } else {
                throw new RuntimeException("服务器返回了非JSON格式的响应");
            }
        } catch (Exception e) {
            throw new RuntimeException("请求历年高校招生计划数据失败: " + e.getMessage(), e);
        }
    }

    /**
     * 从JSON响应中提取历年高校招生计划数据
     * @param json JSON响应字符串
     * @return 历年高校招生计划数据列表
     */
    public static List<CollegeEnrollmentPlanInfo> extractCollegeEnrollmentPlanInfo(String json) {
        try {
            // 检查JSON是否有效
            if (json == null || json.isEmpty() || !json.contains("Data")) {
                throw new RuntimeException("无效的JSON响应或缺少Data字段");
            }

            // 使用Jackson的ObjectMapper直接解析JSON
            com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
            // 配置ObjectMapper以处理各种特殊情况
            objectMapper.configure(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            objectMapper.configure(com.fasterxml.jackson.databind.DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
            objectMapper.configure(com.fasterxml.jackson.databind.DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);

            com.fasterxml.jackson.databind.JsonNode rootNode = objectMapper.readTree(json);
            com.fasterxml.jackson.databind.JsonNode dataNode = rootNode.get("Data");

            if (dataNode == null || !dataNode.isArray()) {
                System.err.println("无法获取Data数组节点");
                return new ArrayList<>();
            }

            try {
                // 使用TypeReference指定返回类型
                return objectMapper.readValue(
                        dataNode.toString(),
                        objectMapper.getTypeFactory().constructCollectionType(List.class, CollegeEnrollmentPlanInfo.class)
                );
            } catch (Exception e) {
                System.err.println("解析Data数组失败: " + e.getMessage());

                // 尝试逐个解析元素
                List<CollegeEnrollmentPlanInfo> result = new ArrayList<>();
                for (int i = 0; i < dataNode.size(); i++) {
                    try {
                        com.fasterxml.jackson.databind.JsonNode itemNode = dataNode.get(i);
                        CollegeEnrollmentPlanInfo item = objectMapper.readValue(itemNode.toString(), CollegeEnrollmentPlanInfo.class);
                        result.add(item);
                    } catch (Exception ex) {
                        System.err.println("解析第" + (i + 1) + "个元素失败: " + ex.getMessage());
                    }
                }

                if (!result.isEmpty()) {
                    return result;
                }
                throw e; // 如果所有元素都解析失败，则抛出原始异常
            }
        } catch (Exception e) {
            throw new RuntimeException("解析历年高校招生计划数据失败: " + e.getMessage(), e);
        }
    }

    /**
     * 获取历年高校招生计划数据总数量
     * @param json API响应的JSON字符串
     * @return 数据总数量，如果无法获取则返回-1
     */
    public static int getCollegeEnrollmentPlanTotalCount(String json) {
        try {
            // 使用Jackson的ObjectMapper直接解析JSON
            com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
            com.fasterxml.jackson.databind.JsonNode rootNode = objectMapper.readTree(json);
            com.fasterxml.jackson.databind.JsonNode dataStatusNode = rootNode.get("DataStatus");

            if (dataStatusNode != null && dataStatusNode.has("DataTotalCount")) {
                com.fasterxml.jackson.databind.JsonNode totalCountNode = dataStatusNode.get("DataTotalCount");
                if (totalCountNode.isNumber()) {
                    return totalCountNode.asInt();
                } else if (totalCountNode.isTextual()) {
                    return Integer.parseInt(totalCountNode.asText());
                }
            }
        } catch (Exception e) {
            // 解析异常时返回-1
            System.err.println("解析历年高校招生计划数据总数量失败: " + e.getMessage());
        }
        return -1;
    }

    /**
     * 查询历年高校招生计划数据（带缓存）
     * @param reqVO 查询参数
     * @return 历年高校招生计划数据和总数量
     */
    public static Map<String, Object> getCollegeEnrollmentPlanInfo(CollegeEnrollmentPlanQueryReqVO reqVO) {
        // 生成缓存键
        String cacheKey = generateEnrollmentPlanCacheKey(reqVO);

        // 这里由于是静态方法，无法直接使用Spring的缓存注解
        // 建议将此方法移到Service层并使用缓存注解
        // 目前先保持原有逻辑，在调用方法中实现缓存

        Map<String, Object> result = new HashMap<>();

        try {
            // 获取JSON响应
            String json = getCollegeEnrollmentPlanJson(reqVO);

            // 提取历年高校招生计划数据
            List<CollegeEnrollmentPlanInfo> enrollmentPlanList = extractCollegeEnrollmentPlanInfo(json);

            // 获取总数量
            int totalCount = getCollegeEnrollmentPlanTotalCount(json);

            // 构建返回结果
            result.put("success", true);
            result.put("enrollmentPlanList", enrollmentPlanList);
            result.put("totalCount", totalCount);
            result.put("pageIndex", reqVO.getPageIndex());
            result.put("pageSize", reqVO.getPageSize());

            // 计算总页数
            int totalPages = (int) Math.ceil((double) totalCount / reqVO.getPageSize());
            result.put("totalPages", totalPages);

            return result;
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询历年高校招生计划数据失败: " + e.getMessage());
            return result;
        }
    }

    /**
     * 生成招生计划缓存键
     * @param reqVO 查询参数
     * @return 缓存键
     */
    private static String generateEnrollmentPlanCacheKey(CollegeEnrollmentPlanQueryReqVO reqVO) {
        StringBuilder keyBuilder = new StringBuilder();
        keyBuilder.append("enrollment_plan:");

        if (reqVO.getSchoolName() != null) {
            keyBuilder.append("school:").append(reqVO.getSchoolName()).append(":");
        }
        if (reqVO.getCollegeMajorName() != null) {
            keyBuilder.append("major:").append(reqVO.getCollegeMajorName()).append(":");
        }
        if (reqVO.getProvinceName() != null) {
            keyBuilder.append("province:").append(reqVO.getProvinceName()).append(":");
        }
        if (reqVO.getType() != null) {
            keyBuilder.append("type:").append(reqVO.getType()).append(":");
        }
        if (reqVO.getYear() != null) {
            keyBuilder.append("year:").append(reqVO.getYear()).append(":");
        }

        keyBuilder.append("page:").append(reqVO.getPageIndex());
        keyBuilder.append(":size:").append(reqVO.getPageSize());

        return keyBuilder.toString();
    }

    /**
     * 查询历年高考省录取分数线数据
     * @param reqVO 查询参数
     * @return 省录取分数线数据JSON字符串
     */
    public static String getProvinceScoreJson(ProvinceScoreQueryReqVO reqVO) {
        try {
            // 请求频率控制
            long currentTime = System.currentTimeMillis();
            long elapsedTime = currentTime - lastRequestTime;
            if (lastRequestTime > 0 && elapsedTime < MIN_REQUEST_INTERVAL) {
                // 如果距离上次请求的时间小于最小间隔，则等待
                long sleepTime = MIN_REQUEST_INTERVAL - elapsedTime;
                Thread.sleep(sleepTime);
            }

            Map<String, String> header = new HashMap<>();
            // 添加请求头信息
            header.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
            header.put("Accept", "application/json");

            // 构建请求URL
            StringBuilder urlBuilder = new StringBuilder(apibase + "/metadata/ceeprovince?appkey=" + apiKey_province);

            // 添加参数
            if (reqVO.getKeyword() != null && !reqVO.getKeyword().isEmpty()) {
                urlBuilder.append("&keyword=").append(java.net.URLEncoder.encode(reqVO.getKeyword(), "UTF-8"));
            } else {
                urlBuilder.append("&keyword=");
            }

            if (reqVO.getYear() != null && reqVO.getYear() != 0) {
                urlBuilder.append("&year=").append(reqVO.getYear());
            } else {
                urlBuilder.append("&year=");
            }

            if (reqVO.getCategory() != null && !reqVO.getCategory().isEmpty()) {
                urlBuilder.append("&category=").append(java.net.URLEncoder.encode(reqVO.getCategory(), "UTF-8"));
            } else {
                urlBuilder.append("&category=");
            }

            String url = urlBuilder.toString();

            // 发送请求并记录时间
            lastRequestTime = System.currentTimeMillis();
            String response = HttpUtils.get(url, header);

            // 检查响应是否是JSON格式
            if (response != null && (response.startsWith("{") || response.startsWith("["))) {
                return response;
            } else {
                throw new RuntimeException("服务器返回了非JSON格式的响应");
            }
        } catch (Exception e) {
            throw new RuntimeException("请求历年高考省录取分数线数据失败: " + e.getMessage(), e);
        }
    }

    /**
     * 从JSON响应中提取历年高考省录取分数线数据
     * @param json JSON响应字符串
     * @return 历年高考省录取分数线数据列表
     */
    public static List<ProvinceScoreInfo> extractProvinceScoreInfo(String json) {
        try {
            // 检查JSON是否有效
            if (json == null || json.isEmpty() || !json.contains("Data")) {
                throw new RuntimeException("无效的JSON响应或缺少Data字段");
            }

            // 使用Jackson的ObjectMapper直接解析JSON
            com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
            // 配置ObjectMapper以处理各种特殊情况
            objectMapper.configure(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            objectMapper.configure(com.fasterxml.jackson.databind.DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
            objectMapper.configure(com.fasterxml.jackson.databind.DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);

            com.fasterxml.jackson.databind.JsonNode rootNode = objectMapper.readTree(json);
            com.fasterxml.jackson.databind.JsonNode dataNode = rootNode.get("Data");

            if (dataNode == null || !dataNode.isArray()) {
                System.err.println("无法获取Data数组节点");
                return new ArrayList<>();
            }

            try {
                // 使用TypeReference指定返回类型
                return objectMapper.readValue(
                        dataNode.toString(),
                        objectMapper.getTypeFactory().constructCollectionType(List.class, ProvinceScoreInfo.class)
                );
            } catch (Exception e) {
                System.err.println("解析Data数组失败: " + e.getMessage());

                // 尝试逐个解析元素
                List<ProvinceScoreInfo> result = new ArrayList<>();
                for (int i = 0; i < dataNode.size(); i++) {
                    try {
                        com.fasterxml.jackson.databind.JsonNode itemNode = dataNode.get(i);
                        ProvinceScoreInfo item = objectMapper.readValue(itemNode.toString(), ProvinceScoreInfo.class);
                        result.add(item);
                    } catch (Exception ex) {
                        System.err.println("解析第" + (i + 1) + "个元素失败: " + ex.getMessage());
                    }
                }

                if (!result.isEmpty()) {
                    return result;
                }
                throw e; // 如果所有元素都解析失败，则抛出原始异常
            }
        } catch (Exception e) {
            throw new RuntimeException("解析历年高考省录取分数线数据失败: " + e.getMessage(), e);
        }
    }

    /**
     * 获取历年高考省录取分数线数据总数量
     * @param json API响应的JSON字符串
     * @return 数据总数量，如果无法获取则返回-1
     */
    public static int getProvinceScoreTotalCount(String json) {
        try {
            // 使用Jackson的ObjectMapper直接解析JSON
            com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
            com.fasterxml.jackson.databind.JsonNode rootNode = objectMapper.readTree(json);
            com.fasterxml.jackson.databind.JsonNode dataStatusNode = rootNode.get("DataStatus");

            if (dataStatusNode != null && dataStatusNode.has("DataTotalCount")) {
                com.fasterxml.jackson.databind.JsonNode totalCountNode = dataStatusNode.get("DataTotalCount");
                if (totalCountNode.isNumber()) {
                    return totalCountNode.asInt();
                } else if (totalCountNode.isTextual()) {
                    return Integer.parseInt(totalCountNode.asText());
                }
            }
        } catch (Exception e) {
            // 解析异常时返回-1
            System.err.println("解析历年高考省录取分数线数据总数量失败: " + e.getMessage());
        }
        return -1;
    }

    /**
     * 查询历年高考省录取分数线数据
     * @param reqVO 查询参数
     * @return 历年高考省录取分数线数据和总数量
     */
    public static Map<String, Object> getProvinceScoreInfo(ProvinceScoreQueryReqVO reqVO) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 获取JSON响应
            String json = getProvinceScoreJson(reqVO);

            // 提取历年高考省录取分数线数据
            List<ProvinceScoreInfo> provinceScoreList = extractProvinceScoreInfo(json);

            // 获取总数量
            int totalCount = getProvinceScoreTotalCount(json);

            // 构建返回结果
            result.put("success", true);
            result.put("provinceScoreList", provinceScoreList);
            result.put("totalCount", totalCount);

            return result;
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询历年高考省录取分数线数据失败: " + e.getMessage());
            return result;
        }
    }

    /**
     * 查询历年高考高校录取分数线数据
     * @param reqVO 查询参数
     * @return 高校录取分数线数据JSON字符串
     */
    public static String getCollegeScoreJson(CollegeScoreQueryReqVO reqVO) {
        try {
            // 请求频率控制
            long currentTime = System.currentTimeMillis();
            long elapsedTime = currentTime - lastRequestTime;
            if (lastRequestTime > 0 && elapsedTime < MIN_REQUEST_INTERVAL) {
                // 如果距离上次请求的时间小于最小间隔，则等待
                long sleepTime = MIN_REQUEST_INTERVAL - elapsedTime;
                Thread.sleep(sleepTime);
            }

            Map<String, String> header = new HashMap<>();
            // 添加请求头信息
            header.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
            header.put("Accept", "application/json");

            // 构建请求URL
            StringBuilder urlBuilder = new StringBuilder(apibase + "/metadata/ceecollegeline?appkey=" + apiKey_school_score);

            // 添加必需参数
            urlBuilder.append("&searchtype=").append(java.net.URLEncoder.encode(reqVO.getSearchtype(), "UTF-8"));
            urlBuilder.append("&keyword=").append(java.net.URLEncoder.encode(reqVO.getKeyword(), "UTF-8"));
            urlBuilder.append("&pageindex=").append(reqVO.getPageindex());
            urlBuilder.append("&pagesize=").append(reqVO.getPagesize());

            // 添加可选参数
            if (reqVO.getYear() != null && reqVO.getYear() != 0) {
                urlBuilder.append("&year=").append(reqVO.getYear());
            }

            if (reqVO.getMin() != null && reqVO.getMin() != 0) {
                urlBuilder.append("&min=").append(reqVO.getMin());
            }

            if (reqVO.getType() != null && !reqVO.getType().isEmpty()) {
                urlBuilder.append("&type=").append(java.net.URLEncoder.encode(reqVO.getType(), "UTF-8"));
            }

            if (reqVO.getKeywordstrict() != null) {
                urlBuilder.append("&keywordstrict=").append(reqVO.getKeywordstrict());
            }

            if (reqVO.getEnrollprovince() != null && !reqVO.getEnrollprovince().isEmpty()) {
                urlBuilder.append("&enrollprovince=").append(java.net.URLEncoder.encode(reqVO.getEnrollprovince(), "UTF-8"));
            }

            if (reqVO.getBatchname() != null && !reqVO.getBatchname().isEmpty()) {
                urlBuilder.append("&batchname=").append(java.net.URLEncoder.encode(reqVO.getBatchname(), "UTF-8"));
            }

            if (reqVO.getCollegeprovincename() != null && !reqVO.getCollegeprovincename().isEmpty()) {
                urlBuilder.append("&collegeprovincename=").append(java.net.URLEncoder.encode(reqVO.getCollegeprovincename(), "UTF-8"));
            }

            if (reqVO.getEnrollmenttype() != null && !reqVO.getEnrollmenttype().isEmpty()) {
                urlBuilder.append("&enrollmenttype=").append(java.net.URLEncoder.encode(reqVO.getEnrollmenttype(), "UTF-8"));
            }

            if (reqVO.getSchooluuid() != null && !reqVO.getSchooluuid().isEmpty()) {
                urlBuilder.append("&schooluuid=").append(reqVO.getSchooluuid());
            }

            if (reqVO.getSort() != null && !reqVO.getSort().isEmpty()) {
                urlBuilder.append("&sort=").append(java.net.URLEncoder.encode(reqVO.getSort(), "UTF-8"));
            }

            if (reqVO.getMinrange() != null && !reqVO.getMinrange().isEmpty()) {
                urlBuilder.append("&minrange=").append(reqVO.getMinrange());
            }

            String url = urlBuilder.toString();

            // 发送请求并记录时间
            lastRequestTime = System.currentTimeMillis();
            String response = HttpUtils.get(url, header);

            // 检查响应是否是JSON格式
            if (response != null && (response.startsWith("{") || response.startsWith("["))) {
                return response;
            } else {
                throw new RuntimeException("服务器返回了非JSON格式的响应");
            }
        } catch (Exception e) {
            throw new RuntimeException("请求历年高考高校录取分数线数据失败: " + e.getMessage(), e);
        }
    }

    /**
     * 从JSON响应中提取历年高考高校录取分数线数据
     * @param json JSON响应字符串
     * @return 历年高考高校录取分数线数据列表
     */
    public static List<CollegeScoreInfo> extractCollegeScoreInfo(String json) {
        try {
            // 检查JSON是否有效
            if (json == null || json.isEmpty() || !json.contains("Data")) {
                throw new RuntimeException("无效的JSON响应或缺少Data字段");
            }

            // 使用Jackson的ObjectMapper直接解析JSON
            com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
            // 配置ObjectMapper以处理各种特殊情况
            objectMapper.configure(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            objectMapper.configure(com.fasterxml.jackson.databind.DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
            objectMapper.configure(com.fasterxml.jackson.databind.DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);

            com.fasterxml.jackson.databind.JsonNode rootNode = objectMapper.readTree(json);
            com.fasterxml.jackson.databind.JsonNode dataNode = rootNode.get("Data");

            if (dataNode == null || !dataNode.isArray()) {
                System.err.println("无法获取Data数组节点");
                return new ArrayList<>();
            }

            try {
                // 使用TypeReference指定返回类型
                return objectMapper.readValue(
                        dataNode.toString(),
                        objectMapper.getTypeFactory().constructCollectionType(List.class, CollegeScoreInfo.class)
                );
            } catch (Exception e) {
                System.err.println("解析Data数组失败: " + e.getMessage());

                // 尝试逐个解析元素
                List<CollegeScoreInfo> result = new ArrayList<>();
                for (int i = 0; i < dataNode.size(); i++) {
                    try {
                        com.fasterxml.jackson.databind.JsonNode itemNode = dataNode.get(i);
                        CollegeScoreInfo item = objectMapper.readValue(itemNode.toString(), CollegeScoreInfo.class);
                        result.add(item);
                    } catch (Exception ex) {
                        System.err.println("解析第" + (i + 1) + "个元素失败: " + ex.getMessage());
                    }
                }

                if (!result.isEmpty()) {
                    return result;
                }
                throw e; // 如果所有元素都解析失败，则抛出原始异常
            }
        } catch (Exception e) {
            throw new RuntimeException("解析历年高考高校录取分数线数据失败: " + e.getMessage(), e);
        }
    }

    /**
     * 获取历年高考高校录取分数线数据总数量
     * @param json API响应的JSON字符串
     * @return 数据总数量，如果无法获取则返回-1
     */
    public static int getCollegeScoreTotalCount(String json) {
        try {
            // 使用Jackson的ObjectMapper直接解析JSON
            com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
            com.fasterxml.jackson.databind.JsonNode rootNode = objectMapper.readTree(json);
            com.fasterxml.jackson.databind.JsonNode dataStatusNode = rootNode.get("DataStatus");

            if (dataStatusNode != null && dataStatusNode.has("DataTotalCount")) {
                com.fasterxml.jackson.databind.JsonNode totalCountNode = dataStatusNode.get("DataTotalCount");
                if (totalCountNode.isNumber()) {
                    return totalCountNode.asInt();
                } else if (totalCountNode.isTextual()) {
                    return Integer.parseInt(totalCountNode.asText());
                }
            }
        } catch (Exception e) {
            // 解析异常时返回-1
            System.err.println("解析历年高考高校录取分数线数据总数量失败: " + e.getMessage());
        }
        return -1;
    }

    /**
     * 查询历年高考高校录取分数线数据
     * @param reqVO 查询参数
     * @return 历年高考高校录取分数线数据和总数量
     */
    public static Map<String, Object> getCollegeScoreInfo(CollegeScoreQueryReqVO reqVO) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 检查必需参数
            if ((reqVO.getSearchtype() == null || reqVO.getSearchtype().isEmpty()) ||
                (reqVO.getKeyword() == null || reqVO.getKeyword().isEmpty())) {
                result.put("success", false);
                result.put("message", "searchtype和keyword参数不能为空");
                return result;
            }

            // 获取JSON响应
            String json = getCollegeScoreJson(reqVO);

            // 提取历年高考高校录取分数线数据
            List<CollegeScoreInfo> collegeScoreList = extractCollegeScoreInfo(json);

            // 获取总数量
            int totalCount = getCollegeScoreTotalCount(json);

            // 构建返回结果
            result.put("success", true);
            result.put("collegeScoreList", collegeScoreList);
            result.put("totalCount", totalCount);
            result.put("pageIndex", reqVO.getPageindex());
            result.put("pageSize", reqVO.getPagesize());

            // 计算总页数
            int totalPages = (int) Math.ceil((double) totalCount / reqVO.getPagesize());
            result.put("totalPages", totalPages);

            return result;
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询历年高考高校录取分数线数据失败: " + e.getMessage());
            return result;
        }
    }

    /**
     * 查询全球QS世界大学排名数据
     * @param reqVO 查询参数
     * @return QS排名数据JSON字符串
     */
    public static String getQsRankingJson(QsRankingQueryReqVO reqVO) {
        try {
            // 请求频率控制
            long currentTime = System.currentTimeMillis();
            long elapsedTime = currentTime - lastRequestTime;
            if (lastRequestTime > 0 && elapsedTime < MIN_REQUEST_INTERVAL) {
                // 如果距离上次请求的时间小于最小间隔，则等待
                long sleepTime = MIN_REQUEST_INTERVAL - elapsedTime;
                Thread.sleep(sleepTime);
            }

            Map<String, String> header = new HashMap<>();
            // 添加请求头信息
            header.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
            header.put("Accept", "application/json");

            // 构建请求URL
            StringBuilder urlBuilder = new StringBuilder(apibase + "/metadata/global-university-ranking?appkey=" + apiKey_qs_ranking);

            // 添加可选参数
            if (reqVO.getName() != null && !reqVO.getName().isEmpty()) {
                urlBuilder.append("&name=").append(java.net.URLEncoder.encode(reqVO.getName(), "UTF-8"));
            } else {
                urlBuilder.append("&name=");
            }

            urlBuilder.append("&pageindex=").append(reqVO.getPageindex());
            urlBuilder.append("&pagesize=").append(reqVO.getPagesize());

            String url = urlBuilder.toString();

            // 发送请求并记录时间
            lastRequestTime = System.currentTimeMillis();
            String response = HttpUtils.get(url, header);

            // 检查响应是否是JSON格式
            if (response != null && (response.startsWith("{") || response.startsWith("["))) {
                return response;
            } else {
                throw new RuntimeException("服务器返回了非JSON格式的响应");
            }
        } catch (Exception e) {
            throw new RuntimeException("请求全球QS世界大学排名数据失败: " + e.getMessage(), e);
        }
    }

    /**
     * 从JSON响应中提取全球QS世界大学排名数据
     * @param json JSON响应字符串
     * @return QS排名数据列表
     */
    public static List<QsRankingInfo> extractQsRankingInfo(String json) {
        try {
            // 检查JSON是否有效
            if (json == null || json.isEmpty()) {
                System.err.println("JSON响应为空");
                throw new RuntimeException("JSON响应为空");
            }

            // 打印原始JSON响应用于调试
            System.out.println("QS排名API原始响应: " + json.substring(0, Math.min(500, json.length())) + "...");

            if (!json.contains("Data")) {
                System.err.println("JSON响应中缺少Data字段");
                throw new RuntimeException("JSON响应中缺少Data字段");
            }

            // 使用Jackson的ObjectMapper直接解析JSON
            com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
            // 配置ObjectMapper以处理各种特殊情况
            objectMapper.configure(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            objectMapper.configure(com.fasterxml.jackson.databind.DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
            objectMapper.configure(com.fasterxml.jackson.databind.DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);

            com.fasterxml.jackson.databind.JsonNode rootNode = objectMapper.readTree(json);

            // 检查DataStatus
            com.fasterxml.jackson.databind.JsonNode dataStatusNode = rootNode.get("DataStatus");
            if (dataStatusNode != null) {
                com.fasterxml.jackson.databind.JsonNode statusCodeNode = dataStatusNode.get("StatusCode");
                com.fasterxml.jackson.databind.JsonNode statusDescNode = dataStatusNode.get("StatusDescription");
                if (statusCodeNode != null && statusDescNode != null) {
                    int statusCode = statusCodeNode.asInt();
                    String statusDesc = statusDescNode.asText();
                    System.out.println("API状态码: " + statusCode + ", 状态描述: " + statusDesc);

                    if (statusCode != 100) {
                        throw new RuntimeException("API调用失败: " + statusDesc + " (状态码: " + statusCode + ")");
                    }
                }
            }

            com.fasterxml.jackson.databind.JsonNode dataNode = rootNode.get("Data");

            if (dataNode == null) {
                System.err.println("Data节点为null");
                return new ArrayList<>();
            }

            if (dataNode.isNull()) {
                System.err.println("Data节点值为null");
                return new ArrayList<>();
            }

            if (!dataNode.isArray()) {
                System.err.println("Data节点不是数组类型，实际类型: " + dataNode.getNodeType());
                return new ArrayList<>();
            }

            try {
                // 使用TypeReference指定返回类型
                return objectMapper.readValue(
                        dataNode.toString(),
                        objectMapper.getTypeFactory().constructCollectionType(List.class, QsRankingInfo.class)
                );
            } catch (Exception e) {
                System.err.println("解析Data数组失败: " + e.getMessage());

                // 尝试逐个解析元素
                List<QsRankingInfo> result = new ArrayList<>();
                for (int i = 0; i < dataNode.size(); i++) {
                    try {
                        com.fasterxml.jackson.databind.JsonNode itemNode = dataNode.get(i);
                        QsRankingInfo item = objectMapper.readValue(itemNode.toString(), QsRankingInfo.class);
                        result.add(item);
                    } catch (Exception ex) {
                        System.err.println("解析第" + (i + 1) + "个元素失败: " + ex.getMessage());
                    }
                }

                if (!result.isEmpty()) {
                    return result;
                }
                throw e; // 如果所有元素都解析失败，则抛出原始异常
            }
        } catch (Exception e) {
            throw new RuntimeException("解析全球QS世界大学排名数据失败: " + e.getMessage(), e);
        }
    }

    /**
     * 获取全球QS世界大学排名数据总数量
     * @param json API响应的JSON字符串
     * @return 数据总数量，如果无法获取则返回-1
     */
    public static int getQsRankingTotalCount(String json) {
        try {
            // 使用Jackson的ObjectMapper直接解析JSON
            com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
            com.fasterxml.jackson.databind.JsonNode rootNode = objectMapper.readTree(json);
            com.fasterxml.jackson.databind.JsonNode dataStatusNode = rootNode.get("DataStatus");

            if (dataStatusNode != null && dataStatusNode.has("DataTotalCount")) {
                com.fasterxml.jackson.databind.JsonNode totalCountNode = dataStatusNode.get("DataTotalCount");
                if (totalCountNode.isNumber()) {
                    return totalCountNode.asInt();
                } else if (totalCountNode.isTextual()) {
                    return Integer.parseInt(totalCountNode.asText());
                }
            }
        } catch (Exception e) {
            // 解析异常时返回-1
            System.err.println("解析全球QS世界大学排名数据总数量失败: " + e.getMessage());
        }
        return -1;
    }

    /**
     * 查询全球QS世界大学排名数据
     * @param reqVO 查询参数
     * @return QS排名数据和总数量
     */
    public static Map<String, Object> getQsRankingInfo(QsRankingQueryReqVO reqVO) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 获取JSON响应
            String json = getQsRankingJson(reqVO);

            // 提取QS排名数据
            List<QsRankingInfo> qsRankingList = extractQsRankingInfo(json);

            // 获取总数量
            int totalCount = getQsRankingTotalCount(json);

            // 构建返回结果
            result.put("success", true);
            result.put("qsRankingList", qsRankingList);
            result.put("totalCount", totalCount);
            result.put("pageIndex", reqVO.getPageindex());
            result.put("pageSize", reqVO.getPagesize());

            // 计算总页数
            int totalPages = (int) Math.ceil((double) totalCount / reqVO.getPagesize());
            result.put("totalPages", totalPages);

            return result;
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询全球QS世界大学排名数据失败: " + e.getMessage());
            return result;
        }
    }
}
